<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title">申请管理</view>
        <view class="uni-sub-title">管理所有测试账号申请信息</view>
      </view>
      <view class="uni-group">
        <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
        <button class="uni-button" type="default" size="mini" @click="search">搜索</button>
        <button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
        <button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length" @click="delTable">批量删除</button>
        <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <button class="uni-button" type="primary" size="mini">导出 Excel</button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db ref="udb" :collection="collectionList" field="company,contact,phone,exchange,accountCount,futuresCompany,futuresContact,status,createTime,updateTime,ip,userAgent" :where="where" page-data="replace"
        :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
        v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual" @load="onqueryload">
        <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
          <uni-tr>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'company')" sortable @sort-change="sortChange($event, 'company')">所属公司</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'contact')" sortable @sort-change="sortChange($event, 'contact')">联系人</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'phone')" sortable @sort-change="sortChange($event, 'phone')">联系方式</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.exchange_localdata" @filter-change="filterChange($event, 'exchange')">待测试交易所</uni-th>
            <uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'accountCount')" sortable @sort-change="sortChange($event, 'accountCount')">测试账号数量</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'futuresCompany')" sortable @sort-change="sortChange($event, 'futuresCompany')">所属期货公司</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'futuresContact')" sortable @sort-change="sortChange($event, 'futuresContact')">期货公司对接人</uni-th>
            <uni-th align="center" filter-type="select" :filter-data="options.filterData.status_localdata" @filter-change="filterChange($event, 'status')">申请状态</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'createTime')" sortable @sort-change="sortChange($event, 'createTime')">创建时间</uni-th>
            <uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'updateTime')" sortable @sort-change="sortChange($event, 'updateTime')">更新时间</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'ip')" sortable @sort-change="sortChange($event, 'ip')">提交IP地址</uni-th>
            <uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'userAgent')" sortable @sort-change="sortChange($event, 'userAgent')">用户代理</uni-th>
            <uni-th align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item,index) in data" :key="index">
            <uni-td align="center">{{item.company}}</uni-td>
            <uni-td align="center">{{item.contact}}</uni-td>
            <uni-td align="center">{{item.phone}}</uni-td>
            <uni-td align="center">{{options.exchange_valuetotext[item.exchange]}}</uni-td>
            <uni-td align="center">{{item.accountCount}}</uni-td>
            <uni-td align="center">{{item.futuresCompany}}</uni-td>
            <uni-td align="center">{{item.futuresContact}}</uni-td>
            <uni-td align="center">
              <span :class="`status-tag status-${item.status.toLowerCase()}`">{{options.status_valuetotext[item.status]}}</span>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.createTime"></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.updateTime"></uni-dateformat>
            </uni-td>
            <uni-td align="center">{{item.ip}}</uni-td>
            <uni-td align="center">{{item.userAgent}}</uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini" type="primary">编辑</button>
                <button @click="quickEditStatus(item)" class="uni-button" size="mini" type="default">状态</button>
                <button @click="confirmDelete(item._id)" class="uni-button" size="mini" type="warn">删除</button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/acc.js';

  function numberRange(start, end) {
    return Array.from(new Array(end + 1).keys()).slice(start);
  }

  const db = uniCloud.database()
  // 表查询配置
  const dbOrderBy = '' // 排序字段
  const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

  export default {
    data() {
      return {
        collectionList: "acc",
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            "exchange_localdata": [
              {
                "value": "上期/能源所",
                "text": "上期/能源所"
              },
              {
                "value": "中金所",
                "text": "中金所"
              },
              {
                "value": "大商所",
                "text": "大商所"
              },
              {
                "value": "郑商所",
                "text": "郑商所"
              },
              {
                "value": "广期所",
                "text": "广期所"
              }
            ],
            "accountCount_data": numberRange(1, 100),
            "accountCount_index": null,
            "status_localdata": [
              {
                "value": "pending",
                "text": "待审核"
              },
              {
                "value": "approved",
                "text": "已通过"
              },
              {
                "value": "rejected",
                "text": "已拒绝"
              }
            ]
          },
          ...enumConverter
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "acc.xls",
          "type": "xls",
          "fields": {
            "所属公司": "company",
            "联系人": "contact",
            "联系方式": "phone",
            "待测试交易所": "exchange",
            "测试账号数量": "accountCount",
            "所属期货公司": "futuresCompany",
            "期货公司对接人": "futuresContact",
            "申请状态": "status",
            "创建时间": "createTime",
            "更新时间": "updateTime",
            "提交IP地址": "ip",
            "用户代理": "userAgent"
          }
        },
        exportExcelData: []
      }
    },
    onLoad() {
      this._filter = {}
    },
    onReady() {
      this.$refs.udb.loadData()
    },
    methods: {
      onqueryload(data) {
        this.exportExcelData = data
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        const newWhere = this.getWhere()
        this.where = newWhere
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      // 多选处理
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      // 批量删除
      delTable() {
        const selectedCount = this.selectedIndexs.length;
        uni.showModal({
          title: '确认批量删除',
          content: `确定要删除选中的 ${selectedCount} 条申请记录吗？删除后无法恢复。`,
          confirmText: '删除',
          confirmColor: '#ff0000',
          success: (res) => {
            if (res.confirm) {
              this.$refs.udb.remove(this.selectedItems(), {
                success:(res) => {
                  uni.showToast({
                    title: `成功删除 ${selectedCount} 条记录`,
                    icon: 'success'
                  });
                  this.$refs.table.clearSelection()
                },
                fail: (err) => {
                  uni.showModal({
                    content: err.message || '批量删除失败',
                    showCancel: false
                  });
                }
              })
            }
          }
        });
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        uni.showModal({
          title: '确认删除',
          content: '确定要删除这条申请记录吗？删除后无法恢复。',
          confirmText: '删除',
          confirmColor: '#ff0000',
          success: (res) => {
            if (res.confirm) {
              this.$refs.udb.remove(id, {
                success:(res) => {
                  uni.showToast({
                    title: '删除成功',
                    icon: 'success'
                  });
                  this.$refs.table.clearSelection()
                },
                fail: (err) => {
                  uni.showModal({
                    content: err.message || '删除失败',
                    showCancel: false
                  });
                }
              })
            }
          }
        });
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        if (Object.keys(newWhere).length) {
          this.where = newWhere
        } else {
          this.where = ''
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      quickEditStatus(item) {
        const statusOptions = [
          { value: 'pending', text: '待审核' },
          { value: 'approved', text: '已通过' },
          { value: 'rejected', text: '已拒绝' }
        ];
        
        uni.showActionSheet({
          itemList: statusOptions.map(option => option.text),
          success: (res) => {
            const newStatus = statusOptions[res.tapIndex].value;
            if (newStatus !== item.status) {
              this.updateItemStatus(item._id, newStatus);
            }
          }
        });
      },
      updateItemStatus(id, newStatus) {
        uni.showLoading({
          title: '更新中...'
        });
        
        db.collection('acc').doc(id).update({
          status: newStatus,
          updateTime: Date.now()
        }).then((res) => {
          uni.hideLoading();
          uni.showToast({
            title: '状态更新成功',
            icon: 'success'
          });
          // 刷新数据
          this.loadData();
        }).catch((err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.message || '更新失败',
            showCancel: false
          });
        });
      }
    }
  }
</script>

<style>
  .status-tag {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
  }

  .status-tag.status-pending {
    background-color: #ffd700;
    color: #000;
  }

  .status-tag.status-approved {
    background-color: #00ff00;
    color: #000;
  }

  .status-tag.status-rejected {
    background-color: #ff0000;
    color: #fff;
  }
  
  .uni-group {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }
  
  .uni-button {
    border-radius: 4px;
    font-size: 12px;
    padding: 4px 8px;
  }
  
  .uni-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  
  .uni-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
  }
  
  .uni-title {
    color: white;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .uni-sub-title {
    color: rgba(255,255,255,0.8);
    font-size: 14px;
  }
</style>
